package org.dfl.plugin.views.actions;

import java.io.File;
import java.util.GregorianCalendar;

import org.dfl.core.data.IODataManager;
import org.dfl.core.utils.ImageUtils;
import org.dfl.messages.Messages;
import org.dfl.plugin.ProjectConstraints;
import org.dfl.plugin.dialogs.DialogsManager;
import org.dfl.plugin.utils.WorkbenchUtil;
import org.dfl.plugin.views.debug.model.DataTreeElem;
import org.dfl.plugin.views.debug.model.MapKeyTreeElem;
import org.dfl.plugin.views.debug.model.TokenTreeElem;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.actions.ActionDelegate;

/**
 * action that provide saving a content of data or token objects. 
 * It's used in a HistoriesTreeView and TokensTreeView (see mapping in plugin.xml file)
 * @author Piotr Wlodarczyk
 *
 */
public class SaveContentAction extends ActionDelegate {
	
	private IStructuredSelection selection = StructuredSelection.EMPTY;

	/* (non-Javadoc)
	 * @see org.eclipse.ui.actions.ActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
	 */
	public void selectionChanged(IAction action, ISelection sel) {
		if(sel instanceof IStructuredSelection)
			selection = (IStructuredSelection) sel;
		else 
			selection = StructuredSelection.EMPTY;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.actions.ActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action) {
		if(selection.isEmpty()) return;
		Object elem = selection.getFirstElement();
		
		if(elem instanceof MapKeyTreeElem){
			elem = ((MapKeyTreeElem) elem).getChild();
		}
		
		if(elem instanceof DataTreeElem){
			save(((DataTreeElem)elem).getValue());
		}else if(elem instanceof TokenTreeElem){
			save(((TokenTreeElem)elem).getToken().getData());
		}
	}

	private void save(Object value) {
		FileDialog dlg = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);
        
		IProject project = WorkbenchUtil.getCurrentProject();
		String projectPath = project.getLocation().toFile().getAbsolutePath();
		if(new File(projectPath + ProjectConstraints.PROJECT_DIR_DATA).exists()){
			dlg.setFilterPath(projectPath + ProjectConstraints.PROJECT_DIR_DATA);
		}else{
			dlg.setFilterPath(projectPath);
		}
		
		IEditorPart editor = WorkbenchUtil.getActiveEditor();
		String prefix = editor.getEditorInput().getName().replace(".dfl", "")+"_c_";
		prefix += String.format(Messages.FlowRunner_outputFileFormat,  new GregorianCalendar());
		
        // Change the title bar text
        dlg.setText(Messages.SaveContentAction_0);
        if(value instanceof byte[]){
			String ext = ImageUtils.getFormatFromStream((byte[]) value);
			if(ext!=null && !ext.equals("")){ //$NON-NLS-1$
				dlg.setFileName(prefix+"."+ext.toLowerCase()); //$NON-NLS-1$
			}
		}else if(value instanceof String){
			dlg.setFileName(prefix+".txt"); //$NON-NLS-1$
		}else{
			dlg.setFileName(prefix+".xml"); //$NON-NLS-1$
		}
        
        // null if user cancels
        String fileName = dlg.open();
        if (fileName != null) {
        	if(new File(fileName).exists() && !DialogsManager.openOkCancelDialog(Messages.SaveAllTokensAction_9,Messages.SaveAllTokensAction_10)){
        		return;
        	}
        	try {
        		if(value instanceof byte[]){
        			IODataManager.saveBinaryFile(fileName,(byte[])value);
        		}else if(value instanceof String){
        			IODataManager.saveTextFile(fileName, (String) value);
        		}else{
        			IODataManager.saveDataXmlFile(fileName,value);
        		}
        		WorkbenchUtil.refreshProject(project);
			} catch (Exception e) {
				DialogsManager.openErrorDialog(e);
			}
        }
	}
}
